import 'package:flutter/material.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/model/knowledge_model.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

import 'anchor_view.dart';

class FutureBuilderDemoPage extends StatefulWidget {
  @override
  _FutureBuilderDemoPageState createState() => _FutureBuilderDemoPageState();
}

class _FutureBuilderDemoPageState extends State<FutureBuilderDemoPage> {
  /// 下拉刷新控制器
  EasyRefreshController? _easyRefreshController;

  /// 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;

  /// 列表数组模型
  List<KnowledgeModel> _cookInfoList = KnowledgeModelList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool loading = true;
  bool error = false;
  String? errorMsg;

  /// 获取数据
  Future _getRecommendData({bool replace = true}) async {
    try {
      Map<String, dynamic> result =
          await HttpService.getCookFoodData(offset: page * 10);
      KnowledgeModelList knowledgeModelList =
          KnowledgeModelList.fromJson(result['data']);
      if (replace) {
        _cookInfoList = knowledgeModelList.list;
      } else {
        _cookInfoList.addAll(knowledgeModelList.list);
      }
      // setState(() {
      //   page++;
      //   _easyRefreshController!.resetLoadState();
      //   _easyRefreshController!.resetRefreshState();
      //   _easyRefreshController!.finishRefresh();
      //   _easyRefreshController!.finishLoad(noMore: !hasMore);
      // });
      return _cookInfoList;
    } catch (e) {} finally {}
  }

  Future _onRefresh() async {
    if (error) {
      setState(() => error = false);
    }
    page = 1;
    await _getRecommendData();
    // 恢复刷新状态 使onLoad再次可用
    _easyRefreshController!.resetLoadState();
  }

  // 加载回调(null为不开启加载)
  Future _onLoad() async {
    if (hasMore) {
      await _getRecommendData(replace: false);
    }
    // 结束加载
    _easyRefreshController!.finishLoad(noMore: !hasMore);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
    // _getRecommendData();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _easyRefreshController!.dispose();
    _scrollController!.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("FutureBuilder Demo"),
      ),
      body: Container(
        height: 750,
        child: EasyRefresh(
          // 开启首次加载刷新
          firstRefresh: false,
          header: CustomHeaderView(),
          footer: CustomFooterView(),
          controller: _easyRefreshController,
          enableControlFinishRefresh: false,
          enableControlFinishLoad: true,
          onRefresh: _onRefresh,
          onLoad: _getRecommendData,
          child: Center(
            child: FutureBuilder(
              future: _getRecommendData(),
              builder: (context, snapshot) {
                // 请求已结束
                if (snapshot.connectionState == ConnectionState.done) {
                  if (snapshot.hasError) {
                    // 请求失败，显示错误
                    return Text("Error: ${snapshot.error}");
                  } else {
                    // 请求成功，显示数据
                    return ListView.builder(
                        scrollDirection: Axis.vertical,
                        itemCount: _cookInfoList.length,
                        // shrinkWrap: true, //增加
                        itemBuilder: (BuildContext context, int index) {
                          return AnchorView(
                            model: _cookInfoList[index],
                          );
                        });
                  }
                } else {
                  // 请求未结束，显示loading
                  return CircularProgressIndicator();
                }
              },
            ),
          ),
        ),
      ),
    );
  }
}
